package com.leantech.android.browser.dialog

import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import com.leantech.android.browser.databinding.LayoutCheckboxBottomSheetBinding
import com.leantech.android.browser.utils.gone
import com.leantech.android.browser.utils.onThrottleClick
import com.leantech.android.browser.utils.visible
import com.qmuiteam.qmui.skin.QMUISkinManager
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet

class CheckboxBottomSheet private constructor(context: Context, builder: Builder) :
    QMUIBottomSheet(context) {

    private val binding: LayoutCheckboxBottomSheetBinding =
        LayoutCheckboxBottomSheetBinding.inflate(layoutInflater)
    private val adapter: CheckboxAdapter

    private val checkedItems = mutableSetOf<CheckboxItem>()
    private var onItemChecked: ((CheckboxBottomSheet, List<CheckboxItem>) -> Unit)? =
        builder.onItemChecked

    init {
        addContentView(binding.root)

        adapter = CheckboxAdapter() { item, checked ->
            if (checked) {
                checkedItems.add(item)
            } else {
                checkedItems.remove(item)
            }
        }

        setSkinManager(QMUISkinManager.defaultInstance(context))
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        if (builder.title.isNullOrEmpty()) {
            binding.title.gone()
        } else {
            binding.title.visible()
            binding.title.text = builder.title
        }

        adapter.submitList(builder.checkboxItems)

        binding.confirmActionBar.btnSure.onThrottleClick {
            onItemChecked?.invoke(this, checkedItems.toList())
        }

        binding.confirmActionBar.btnCancel.onThrottleClick {
            dismiss()
        }

        setFitNav(true)
        behavior.setAllowDrag(true)
    }

    override fun dismiss() {
        super.dismiss()
        checkedItems.clear()
    }

    data class CheckboxItem(val text: String, val checked: Boolean, val tag: Any? = null)

    class Builder(private val context: Context) {
        internal var title: String? = null
        internal val checkboxItems = mutableListOf<CheckboxItem>()
        internal var onItemChecked: ((CheckboxBottomSheet, List<CheckboxItem>) -> Unit)? = null


        fun addItem(text: String, checked: Boolean = false, tag: Any? = null) = apply {
            checkboxItems.add(CheckboxItem(text, checked, tag))
        }

        fun setTitle(title: String?) = apply {
            this.title = title
        }

        fun setOnItemChecked(onItemCheckedCallback: (CheckboxBottomSheet, List<CheckboxItem>) -> Unit) =
            apply {
                this.onItemChecked = onItemCheckedCallback
            }

        fun build(): CheckboxBottomSheet {
            return CheckboxBottomSheet(context, this)
        }

    }

}